package org.example.lanchain.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.example.lanchain.bean.KnowledgeBase;
import org.example.lanchain.bean.KnowledgeDocument;
import org.example.lanchain.mapper.KnowledgeBaseMapper;
import org.example.lanchain.mapper.KnowledgeDocumentMapper;
import org.example.lanchain.service.KnowledgeBaseService;
import org.example.lanchain.service.KnowledgeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 知识库服务实现类
 */
@Service
public class KnowledgeBaseServiceImpl implements KnowledgeBaseService {

    @Autowired
    private KnowledgeBaseMapper knowledgeBaseMapper;
    
    @Autowired
    private KnowledgeDocumentMapper knowledgeDocumentMapper;
    
    @Autowired
    private KnowledgeService knowledgeService;

    @Override
    public KnowledgeBase createKnowledgeBase(KnowledgeBase knowledgeBase) {
        knowledgeBase.setCreateTime(LocalDateTime.now());
        knowledgeBase.setUpdateTime(LocalDateTime.now());
        knowledgeBaseMapper.insert(knowledgeBase);
        return knowledgeBase;
    }

    @Override
    public KnowledgeBase getKnowledgeBaseById(Long id) {
        return knowledgeBaseMapper.selectById(id);
    }

    @Override
    public List<KnowledgeBase> getAllKnowledgeBases() {
        return knowledgeBaseMapper.selectList(null);
    }

    @Override
    public boolean updateKnowledgeBase(KnowledgeBase knowledgeBase) {
        knowledgeBase.setUpdateTime(LocalDateTime.now());
        return knowledgeBaseMapper.updateById(knowledgeBase) > 0;
    }

    @Override
    public boolean deleteKnowledgeBase(Long id) {
        try {
            // 先删除知识库下的所有文档
            QueryWrapper<KnowledgeDocument> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("knowledge_base_id", id);
            List<KnowledgeDocument> documents = knowledgeDocumentMapper.selectList(queryWrapper);
            
            // 删除每个文档（包括向量数据）
            for (KnowledgeDocument doc : documents) {
                knowledgeService.deleteDocument(doc.getId());
            }
            
            // 删除知识库记录
            return knowledgeBaseMapper.deleteById(id) > 0;
        } catch (Exception e) {
            throw new RuntimeException("删除知识库失败", e);
        }
    }

    @Override
    public List<KnowledgeBase> getKnowledgeBasesByUserId(Long userId) {
        QueryWrapper<KnowledgeBase> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        return knowledgeBaseMapper.selectList(queryWrapper);
    }
} 